package com.yx.cloud.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.iot.base.bean.message.IotMessage;
import com.iot.base.service.req.GetNotificationParam;
import com.iot.common.utils.Event;
import com.iot.common.utils.LogUtils;
import com.iot.product.sweeper.bean.Robot;
import com.iot.sweeper.AppContext;
import com.yx.cloud.Interface.BounceCallBack;
import com.yx.cloud.R;
import com.yx.cloud.activity.MessageWarningActivity;
import com.yx.cloud.header.NormalBounceHandler;
import com.yx.cloud.product.ProductConfigConstants;
import com.yx.cloud.utils.LoadProgressDialog;
import com.yx.cloud.view.BounceLayout;
import com.yx.cloud.view.DefaultFooter;
import com.yx.cloud.view.DefaultHeader;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MessageFragment extends Fragment {
    private ConstraintLayout cl_device_message;
    private FrameLayout fl_message_container;
    private BounceLayout bl_device_message;
    private RecyclerView rv_device_message_list;
    private DeviceMessageAdapter adapter;
    private ImageView iv_message_none;
    private List<DeviceMessageBean> messageBeanList = new ArrayList<>();
    private List<DeviceMessageBean> temp = new ArrayList<>();
    private int deviceRefreshCount;
    private LoadProgressDialog loadProgressDialog;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {
        View view = inflater.inflate(R.layout.message_fragment, null);
        initView(view);
        initData();
        return view;
    }

    private void initView(View view) {
        fl_message_container=view.findViewById(R.id.fl_message_container);
        loadProgressDialog = new LoadProgressDialog(getActivity());
        iv_message_none = view.findViewById(R.id.iv_message_none);
        iv_message_none.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getDeviceMessage();
            }
        });

        rv_device_message_list = view.findViewById(R.id.rv_device_message_list);
        rv_device_message_list.setLayoutManager(new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,false));
        adapter = new DeviceMessageAdapter(getActivity());
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                DeviceMessageBean bean = messageBeanList.get(position);
                Intent intent = new Intent(getActivity(), MessageWarningActivity.class);
                intent.putExtra("device_id", bean.deviceId);
                intent.putExtra("device_name", bean.deviceName);
                startActivity(intent);
            }
        });
        rv_device_message_list.setAdapter(adapter);

        cl_device_message = view.findViewById(R.id.cl_device_message);
        bl_device_message = view.findViewById(R.id.bl_message_message);
        bl_device_message.setEventForwardingHelper((downX, downY, moveX, moveY) -> true);
        bl_device_message.setBounceHandler(new NormalBounceHandler(), rv_device_message_list);//设置滚动冲突的控制类
        bl_device_message.setHeaderView(new DefaultHeader(getActivity()), fl_message_container);//设置刷新头，null意味着没有刷新头，不调用该函数意为着空
        bl_device_message.setFooterView(new DefaultFooter(getActivity()), fl_message_container);//设置刷新头，null意味着没有刷新头，不调用该函数意为着空
        bl_device_message.setBounceCallBack(new BounceCallBack() {
            @Override
            public void startRefresh() {
                getDeviceMessage();
            }

            @Override
            public void startLoadingMore() {
            }
        });


    }

    private void initData() {
        getDeviceMessage();
    }

    public void getDeviceMessage() {
        List<Robot> deviceList = AppContext.get().getDeviceList();
        if (deviceList.size() > 0) {
//            if(loadProgressDialog == null){
//                loadProgressDialog = new LoadProgressDialog(getActivity());
//            }
//            loadProgressDialog.show();
            deviceRefreshCount = deviceList.size();
            temp = new ArrayList<>();
            for (int i = 0; i < deviceRefreshCount; i++) {
                final Robot robot = deviceList.get(i);

                GetNotificationParam param = new GetNotificationParam();
                param.setDeviceId(robot.getDeviceId());
                param.setOffset(0);
                param.setLimit(1);
                param.setStartTime(0);
                param.setEndTime(System.currentTimeMillis());
                AppContext.getAccountService().getNotification(param);
            }
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        if (event.getType() == Event.MESSAGE_TYPE_GET_MESSAGE_LIST) {
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (event.isResult()) {
                List<IotMessage> iotMessageList = (List<IotMessage>) event.getContent();
                if (iotMessageList != null && iotMessageList.size() > 0) {
                    IotMessage iotMessage = iotMessageList.get(0);
                    Robot robot = getDeviceById(iotMessage.getDeviceId());
                    if (robot != null) {
                        DeviceMessageBean deviceMessageBean = new DeviceMessageBean();
                        deviceMessageBean.deviceId = robot.getDeviceId();
                        deviceMessageBean.deviceName = robot.getName();
                        deviceMessageBean.deviceIcon = robot.getConfig().optInt(ProductConfigConstants.robotIconId);
                        deviceMessageBean.messageContent = iotMessage.getContent();
                        deviceMessageBean.messageTime = simpleDateFormat.format(new Date(iotMessage.getTime()));
                        temp.add(deviceMessageBean);
                    }
                }
            }

            deviceRefreshCount--;
            if (deviceRefreshCount == 0) {
                if (loadProgressDialog.isShowing()) {
                    loadProgressDialog.dismiss();
                }
                messageBeanList = temp;
                if (messageBeanList.size() == 0) {
                    iv_message_none.setVisibility(View.VISIBLE);
                    rv_device_message_list.setVisibility(View.GONE);
                } else {
                    iv_message_none.setVisibility(View.GONE);
                    rv_device_message_list.setVisibility(View.VISIBLE);
                }
                adapter.updateData(messageBeanList);
                bl_device_message.setRefreshCompleted();
            }
        }

    }

    private Robot getDeviceById(String id) {
        List<Robot> robotList = AppContext.get().getDeviceList();
        for (int i = 0; i < robotList.size(); i++) {
            Robot robot = robotList.get(i);
            if (robot.getDeviceId().equals(id)) {
                return robot;
            }
        }
        return null;
    }


    interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    public class DeviceMessageAdapter extends RecyclerView.Adapter<DeviceMessageAdapter.ViewHolder> implements View.OnClickListener, View.OnLongClickListener {
        private final static String TAG = "DeviceListDataAdapter";
        private Context mContext;
        private List<DeviceMessageBean> messageList=new ArrayList<>();
        private OnItemClickListener mOnItemClickListener = null;

        public DeviceMessageAdapter(Context context) {
            mContext = context;
        }

        public List<DeviceMessageBean> getMessageList() {
            return messageList;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LogUtils.i("设备列表 --onCreateViewHolder----------");
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_item_device_message, parent, false);
            ViewHolder holder = new ViewHolder(view);
            view.setOnClickListener(this);
            view.setOnLongClickListener(this);
            return holder;
        }


        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            LogUtils.i("设备列表 --onBindViewHolder----------");
            DeviceMessageBean bean = messageList.get(position);
            holder.iv_icon.setImageResource(bean.deviceIcon);
            holder.tv_name.setText(bean.deviceName);
            holder.tv_time.setText(bean.messageTime);
            holder.tv_message.setText(bean.messageContent);

            holder.itemView.setTag(position);
        }

        public void updateData(List<DeviceMessageBean> list) {
            messageList = list;
            notifyDataSetChanged();
        }

        @Override
        public int getItemCount() {
            return messageList.size();
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        /**
         * Item点击事件方法
         * <p>
         * //     * @param listener
         */
        public void setOnItemClickListener(OnItemClickListener listener) {
            this.mOnItemClickListener = listener;
        }


        @Override
        public void onClick(View v) {
            if (mOnItemClickListener != null) {
                mOnItemClickListener.onItemClick(v, (Integer) v.getTag());
            }
        }

        @Override
        public boolean onLongClick(View v) {
//            if (mOnItemClickListener != null) {
//                mOnItemClickListener.onItemClick(v, (Integer) v.getTag());
//            }
            return false;
        }


        class ViewHolder extends RecyclerView.ViewHolder {
            public TextView tv_name, tv_time, tv_message;
            public ImageView iv_icon;

            public ViewHolder(View itemView) {
                super(itemView);
                iv_icon = itemView.findViewById(R.id.iv_message_device_icon);
                tv_name = itemView.findViewById(R.id.tv_message_device_name);
                tv_time = itemView.findViewById(R.id.tv_message_time);
                tv_message = itemView.findViewById(R.id.tv_message);
            }
        }
    }

    class DeviceMessageBean {
        public String deviceId;
        public int deviceIcon;
        public String deviceName;
        public String messageContent;
        public String messageTime;
    }
}
